package com.hddz.comlib.packet;

import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.util.Log;

import com.hddz.comlib.model.Sensor;
import com.hddz.comlib.util.ConvertUtility;

public class RealTimePacket extends Packet {
	private SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd HHmmss");
	private DecimalFormat decimalFormat = new DecimalFormat("0");
	/**
	 * 站号
	 */
	public int stationId;

	/**
	 * 发送时间
	 */
	public Date sendTime;

	/**
	 * 报文序号
	 */
	public int index = -1;

	/**
	 * 发送时间
	 */
	public String sendTimes;

	/**
	 * 传感器数据
	 */
	private List<Sensor> sensors = new ArrayList<Sensor>();

	public int getStationId() {
		return stationId;
	}

	public void setStationId(int stationId) {
		this.stationId = stationId;
	}

	public Date getSendTime() {
		return sendTime;
	}

	public void setSendTime(Date sendTime) {
		this.sendTime = sendTime;
	}

	public List<Sensor> getSensors() {
		return sensors;
	}

	public void setSensors(List<Sensor> sensors) {
		this.sensors = sensors;
	}

	public String getSendTimes() {
		return sendTimes;
	}

	public void setSendTimes(String sendTimes) {
		this.sendTimes = sendTimes;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	/**
	 * 查找通道匹配的传感器
	 * 
	 * @param channelName
	 * @return
	 */
	public Sensor findSensorByName(String channelName) {
		Sensor mSensor = null;
		if (!channelName.equals("")) {
			for (Sensor s : sensors) {
				if (s.getChannel().equals(channelName)) {
					mSensor = s;
					break;
				}
			}
		}
		return mSensor;
	}

	public String getSensorValueByChanel(String channelName) {
		Sensor sensor = findSensorByName(channelName);
		if (sensor != null) {
			return decimalFormat.format(sensor.getValue());
			// return (int) sensor.getValue() + "";
		} else {
			return "-";
		}
	}

	@Override
	public String createViewText() {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();

		sb.append("站号:" + this.stationId);
		sb.append(" 时间:" + this.sendTime);
		sb.append("\r\n");
		for (Sensor s : this.sensors) {

			sb.append("通道:" + s.getChannel());
			sb.append(" 值 :" + s.getValue());
			sb.append("\r\n");
		}
		return sb.toString();
	}

	@Override
	public Boolean parse(List<Byte> data, int start, int len) {
		// TODO Auto-generated method stub
		try {
			// this.sourceText = Utility.BystesToStr(data, start - 3, len + 5);
			Sensor sensor = null;
			int index = start;
			stationId = ((data.get(index) & 0xff) * 256 + (data.get(index + 1) & 0xff)) * 256 + (data.get(index + 2) & 0xff);
			index += 3;
			Date date = new Date();
			sendTime = dateformat.parse(String.format("%04d", date.getYear()) + String.format("%02d", date.getMonth()) + ConvertUtility.BCDToInt(data.get(index) & 0xff) + " "
					+ ConvertUtility.BCDToInt(data.get(index + 1) & 0xff) + String.format("%02d", date.getMinutes()) + String.format("%02d", date.getSeconds()));
			index += 2;
			while (index < start + len - 1)// 留一位是电压
			{
				int no = (data.get(index) & 0xff) % 16;
				int flag = (data.get(index) & 0xff) / 16;
				index++;
				switch (flag) {
				case 1:// 累计流量 P
					sensor = new Sensor();
					sensor.setStationId(stationId);
					sensor.setChannel("P" + no);
					sensor.setValue((data.get(index) & 0xff) * 1000000 + (data.get(index + 1) & 0xff) * 10000 + (data.get(index + 2) & 0xff) * 100 + (data.get(index + 3) & 0xff));
					sensors.add(sensor);
					index += 4;
					break;
				case 2:// K
					sensor = new Sensor();
					sensor.setStationId(stationId);
					sensor.setChannel("K" + no);
					sensor.setValue((data.get(index) & 0xff) - 0x30);
					sensors.add(sensor);
					index++;
					break;
				case 3:// 模拟量 A
					sensor = new Sensor();
					sensor.setStationId(stationId);
					sensor.setChannel("A" + no);
					sensor.setValue(((data.get(index) & 0xff) * 256 + (data.get(index + 1) & 0xff)) / 1000.0);// 模拟量解数据时，除以1000；
					sensors.add(sensor);
					index += 2;
					break;
				case 4:// B
					sensor = new Sensor();
					sensor.setStationId(stationId);
					sensor.setChannel("B" + no);
					sensor.setValue((data.get(index) & 0xff) - 0x30);
					sensors.add(sensor);
					index++;
					break;
				}
			}
			sensor = new Sensor();
			sensor.setStationId(stationId);
			sensor.setChannel("V");
			int v = data.get(index) & 0xff;
			if (v > 100) {
				sensor.setValue(v * 0.02);// 电池电压解数据时，先乘以2，再除以100
			} else {
				sensor.setValue(v / 10.0);// 数值 <= 100，解析方法：数值÷10；
			}
			sensors.add(sensor);
			this.viewText = this.createViewText();
			return true;
		} catch (Exception e) {
			// CLogger.Write("RealTimePacket Parse Error" + e.Message);
			return false;
		}
	}

	@Override
	public Boolean parse(ByteBuffer data, int len) {
		// TODO Auto-generated method stub
		byte[] b = new byte[len];
		try {
			data.get(b, 0, len);
			this.sourceText = ConvertUtility.bystesToStr(b, 0, len);
			Log.d("RealTimePacket_收到=>>", this.sourceText);
			return true;
		} catch (Exception e) {
			Log.d("RealTimePacket Parse Error", e.getMessage());
			return false;
		}
	}

	@Override
	public boolean equals(Object o) {
		// TODO Auto-generated method stub
		if (o.getClass() == RealTimePacket.class && ((RealTimePacket) o).getIndex() == getIndex() && ((RealTimePacket) o).getSendTime().equals(getSendTime())) {
			return true;
		}
		return super.equals(o);
	}
}
